<template>
  <!--  自定义类型6  -->
  <div class="main-wk">
    <el-form ref="ruleForm" :model="formData" class="demo-ruleForm" @submit.native.prevent>
      <el-row :gutter="20" class="top-title">
        <el-col :span="2">序号</el-col>
        <el-col :span="6">名称</el-col>
        <el-col :span="8">规则</el-col>
        <el-col :span="2">操作</el-col>
      </el-row>
      <div v-for="(item, index) in formData.list">
        <el-row class="row" :gutter="20" style="padding: 10px 0">
          <el-col :span="2">{{ index + 1 }}</el-col>
          <el-col :span="6">
            <el-form-item
              :prop="`list.${index}.contextValue`"
              :rules="[{ required: true, message: '请选择', trigger: 'blur' }]"
            >
              <el-select
                v-model="item.contextValue"
                filterable
                placeholder="请选择名称"
                @change="handleChange($event, index)"
              >
                <el-option
                  v-for="(i, childIndex) in nameLists"
                  :key="childIndex"
                  :label="i.customName"
                  :value="i.customId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              :prop="`list.${index}.operators`"
              :rules="[{ required: true, message: '请选择', trigger: 'blur' }]"
            >
              <el-select
                v-model="item.operators"
                filterable
                placeholder="请选择名称"
                @change="handleSecondChange($event, index)"
              >
                <el-option
                  v-for="(i, childIndex) in ruleList"
                  :key="childIndex"
                  :label="i.itemLabel"
                  :value="i.itemVale"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="2">
            <el-button type="text" @click="handleDel(index)">删除</el-button>
          </el-col>
        </el-row>
        <el-row v-if="item.operators == 'custom'" style="padding-bottom: 10px">
          <el-col :span="2"> 字段关系： </el-col>
          <el-col :span="20">
            <logicalJudg
              ref="logicalJudgRef"
              :relation-data="item.relationData"
              :field-obj="searchFormObj"
              :context-list="contextList"
              @addConditions="(data) => addConditions(data, index)"
              @addGroup="addGroup(index)"
              @handleChange="(data) => handleLogicalJudg(data, index)"
            />
          </el-col>
        </el-row>
      </div>
    </el-form>
    <el-button class="row-btn" type="primary" @click="handleAdd">新增一行</el-button>
  </div>
</template>

<script>
import logicalJudg from '@/components/Common/logicalJudg.vue'
import { getDictList } from '@/api/milkyway/accessRules'

export default {
  components: { logicalJudg },
  props: {
    nameList: {
      type: Array,
      default() {
        return []
      }
    },
    contextList: {
      type: Array,
      default() {
        return []
      }
    },
    tableData: {
      type: Array,
      default() {
        return []
      }
    },
    echoData: {
      type: Object,
      default() {
        return {}
      }
    },
    isEdit: {
      type: Boolean,
      default() {
        return false
      }
    }
  },
  data() {
    return {
      formData: {
        list: [
          {
            contextValue: '',
            operators: '',
            relationData: { flag: 'and', subSyntaxExpressnList: [] }
          }
        ]
      },
      isShow: false,
      nameLists: [],
      ruleList: [],
      relationData: {
        flag: 'and',
        subSyntaxExpressnList: []
      },
      // 提交的值
      ruleExpress: [],
      //  逻辑判断
      searchFormObj: {
        fieldList: [
          // 第一个下拉框
          {
            type: 'select',
            field: 'contextValue',
            list: 'contextList'
          },
          // 第二个下拉框
          {
            type: 'select',
            field: 'operators',
            list: 'operatorsList'
          },
          // 第三个下拉框
          {
            type: 'input',
            field: 'matchValue',
            hidden: false
          }
        ],
        searchData: {},
        listTypeInfo: {
          contextList: this.contextList,
          operatorsList: []
        }
      },
      // 第一个下拉框的数据
      firstList: []
    }
  },
  watch: {
    nameList: {
      handler(newVal) {
        if (newVal.length > 0) {
          this.nameLists = newVal
        }
      },
      immediate: true,
      deep: true
    },
    tableData: {
      handler(newVal) {
        const arrList = newVal.map((i) => {
          return { label: i.columnName, value: i.columnValue }
        })
        this.firstList = [...arrList]
      },
      immediate: true,
      deep: true
    },
    echoData: {
      handler(newVal) {
        if (newVal) {
          if (newVal.custom6EchoData) {
            this.formData.list = newVal.custom6EchoData.list
          }
          if (newVal?.ruleExpress) {
            this.ruleExpress = newVal.ruleExpress
          }
        }
      },
      immediate: true,
      deep: true
    }
  },
  mounted() {
    this.getDictList()
  },
  methods: {
    // 点击第一个选择框
    handleChange(value, index) {
      this.ruleExpress[index] = {
        contextValue: '',
        variable: '',
        operators: '',
        relationDatas: {}
      }
      this.ruleExpress[index].contextValue = value
      const currentData = this.nameLists.filter((i) => {
        return i.customId == value
      })
      if (currentData && currentData.length > 0) {
        this.ruleExpress[index].variable = currentData[0].customId
      }
    },
    // 点击第二个选择框
    handleSecondChange(value, index) {
      if (this.ruleExpress[index]) {
        this.ruleExpress[index].operators = value
      } else {
        this.$message.error('请先选择名称')
        this.formData.list[index].operators = ''
      }
    },
    // 新增一行
    handleAdd() {
      this.formData.list.push({
        contextValue: '',
        operators: '',
        relationData: { flag: 'and', subSyntaxExpressnList: [] }
      })
    },
    /** 删除某一行*/
    handleDel(index) {
      this.formData.list.splice(index, 1)
    },
    // 添加条件
    addConditions(data, index) {
      this.formData.list[index].relationData.subSyntaxExpressnList[data].expressionVoList.push({
        contextValue: '',
        matchValue: '',
        operators: '',
        variable: ''
      })
    },
    // 添加条件组
    addGroup(index) {
      this.formData.list[index].relationData.subSyntaxExpressnList.push({
        expressionVoList: [
          {
            contextValue: '',
            matchValue: '',
            operators: '',
            variable: ''
          }
        ],
        flag: ' or '
      })
    },
    // 获取规则
    getDictList() {
      getDictList('colunmExpression').then((res) => {
        this.ruleList = res
      })
    },
    /** 必填项的校验 */
    handleSubmit() {
      return new Promise((resolve, reject) => {
        this.$refs['ruleForm'].validate((valid) => {
          if (valid) {
            if (this.isEdit) {
              this.formData.list.forEach((item, index) => {
                this.handleChange(item.contextValue, index)
                this.ruleExpress[index].contextValue = item.contextValue
                this.ruleExpress[index].operators = item.operators
                this.ruleExpress[index].relationDatas = item.relationData
              })
            }
            resolve({ ruleExpress: this.ruleExpress, formData: this.formData })
            return true
          } else {
            this.$message.error('请完善表单')
            reject('1111111111111111111error submit!!')
            return false
          }
        })
      })
    },
    /** 逻辑判断表单触发的事件 */
    handleLogicalJudg(data, index) {
      if (!this.ruleExpress[index]) {
        this.ruleExpress[index] = {
          contextValue: '',
          variable: '',
          operators: '',
          relationDatas: {}
        }
      }
      this.ruleExpress[index].relationDatas = data
    }
  }
}
</script>

<style lang="scss" scoped>
.main-wk {
  width: 100%;
  padding: 10px;

  .top-title {
    background: #eff4f8;
  }

  .row {
    border-top: 1px solid #e8e8e8;
  }

  .row-btn {
    width: 100%;
  }
}

::v-deep .el-textarea__inner {
  height: 36px !important;
  line-height: 36px !important;
  min-height: auto !important;
}
</style>
